package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.RecordAdapter;
import flc.ast.databinding.ActivityTcpingBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class TcpingActivity extends BaseAc<ActivityTcpingBinding> {

    private String host, port, num;
    private RecordAdapter recordAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_tcping;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivTcpingBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivTcpingShare.setOnClickListener(this);
        mDataBinding.tvStart.setOnClickListener(this);
        mDataBinding.tvClear.setOnClickListener(this);
        mDataBinding.tvScan.setOnClickListener(this);

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        mDataBinding.rvRecordList.setLayoutManager(layoutManager);
        recordAdapter = new RecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivTcpingShare://分享
                String text = mDataBinding.tvTcpingResult.getText().toString().trim();
                if (TextUtils.isEmpty(text)) return;
                IntentUtil.shareText(mContext, text);
                break;
            case R.id.tvStart://开始
                host = mDataBinding.etHost.getText().toString();
                port = mDataBinding.etPort.getText().toString();
                num = mDataBinding.etNum.getText().toString();
                if (TextUtils.isEmpty(host)) {
                    mDataBinding.etHost.requestFocus();
                    ToastUtils.showShort(getString(R.string.please_input_domain_ip));
                    return;
                }
                if (TextUtils.isEmpty(port)) {
                    mDataBinding.etPort.requestFocus();
                    ToastUtils.showShort(getString(R.string.please_input_tcp_port));
                    return;
                }
                if (TextUtils.isEmpty(num)) {
                    mDataBinding.etNum.requestFocus();
                    ToastUtils.showShort(getString(R.string.please_input_tcp_num));
                    return;
                }
                startTcp();
                saveRecord();
                getRecord();
                break;
            case R.id.tvClear://清空
                mDataBinding.etHost.setText("");
                mDataBinding.tvTcpingResult.setText("");
                break;
            case R.id.tvScan://扫描
                getCameraPermission();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mDataBinding.etHost.setText(recordAdapter.getItem(position));
    }

    @Override
    protected void initData() {
        mDataBinding.etPort.setText("80");
        mDataBinding.etNum.setText("5");
        getRecord();
    }

    private void startTcp() {
        showDialog(getString(R.string.loading));
        int count = Integer.parseInt(num);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < count; i++) {
            String line = null;
            try {
                Process pro = Runtime.getRuntime().exec("ping " + host);
                BufferedReader buf = new BufferedReader(new InputStreamReader(
                        pro.getInputStream()));
                line = buf.readLine();
                builder.append(line + "\n");
                buf.close();
            } catch (Exception ex) {

            }
        }
        dismissDialog();
        mDataBinding.tvTcpingResult.setText(builder.toString());
    }

    private void saveRecord() {
        List<String> listSave = new ArrayList<>();
        listSave.add(host);
        List<String> listSp = AppSpUtils.getTcpRecordList();
        if (listSp != null && listSp.size() > 0) {
            listSp.remove(host);
            listSp.add(0, host);
            AppSpUtils.saveTcpRecordList(listSp);
        } else {
            AppSpUtils.saveTcpRecordList(listSave);
        }
    }

    private void getRecord() {
        List<String> listSp = AppSpUtils.getTcpRecordList();
        if (listSp != null && listSp.size() > 0) {
            recordAdapter.setList(listSp);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
        }
    }

    private void getCameraPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA)
                .reqPermissionDesc(getString(R.string.get_scan_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(TcpingActivity.this, ScanQrActivity.class);
                        startActivityForResult(intent, Content.TCP_SCAN);
                    }
                }).request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.TCP_SCAN) {
            String result = data.getStringExtra(Content.result);
            mDataBinding.etHost.setText(result);
        }
    }

}